package com.kool.kmetrics.metrics;

import com.alibaba.fastjson.JSON;
import com.kool.kmetrics.client.RedisClient;
import com.kool.kmetrics.common.constant.ErrorCode;
import com.kool.kmetrics.common.exception.AppException;
import com.kool.kmetrics.consumer.vo.SessionCntLog;
import com.kool.kmetrics.common.util.DateUtil;
import com.kool.kmetrics.common.util.SpringUtil;

import java.text.ParseException;

import static com.kool.kmetrics.constant.MetricsRedisKey.KEY_SESSION_CNT;

/**
 * 当前会话数
 *
 * @author luyu
 */
public class SessionComputer implements MetricsComputer {
    private RedisClient redisClient = SpringUtil.getBean(RedisClient.class);

    /**
     * key过期时长，单位毫秒
     * 3天
     */
    public static final long TIMEOUT_DURING = 259200000L;

    @Override
    public void compute(String log) {
        SessionCntLog sessionCntLog = JSON.parseObject(log, SessionCntLog.class);
        String time = sessionCntLog.getTimestamp();
        int cnt = sessionCntLog.getCnt();

        String minute = null;
        try {
            minute = DateUtil.dateString(DateUtil.parseDate(time, DateUtil.DateFormatEnum.DEFAULT.getFormat()),"yyyyMMddHHmm");
        } catch (ParseException e) {
            throw new AppException(ErrorCode.BUSINESS_ERROR, e, e.getMessage());
        }

        redisClient.set(String.format(KEY_SESSION_CNT, minute), Integer.toString(cnt), TIMEOUT_DURING);
    }
}
